package psn.james.kaixin.module;

import java.util.Calendar;

import org.jdom.Element;

import psn.james.kaixin.KaiXinFarm;
import psn.james.kaixin.po.Farm;
import psn.james.kaixin.util.Network;

public class Thief extends Thread {

	private int retry_times = 5;
	
	private long delay;
	private Farm farm;
	
	public Thief(long delay, Farm farm) {
		super();
		this.delay = delay;
		this.farm = farm;
	}
	
	public Thief(Farm farm) {
		super();
		this.delay = farm.getGrowRemainTime() + farm.getThieveWaitTime() + 1;
		this.farm = farm;
	}
	
	@Override
	public void run() {
		boolean succ = false;
		try {
			sleep(delay);
			succ = thieve();
			while (!succ && --retry_times > 0){
				sleep(30000);
				succ = thieve();
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		farm = null;
	}
	
	private boolean thieve(){
		String baseURL = Network.KAIXINNETWORK + "/!house/!garden/havest.php?";
		String url = baseURL + "farmnum=" + farm.getFarmnum() + "&verify=" + KaiXinFarm.VERIFYCODE +
				"&fuid=" + farm.getOwner().getUid() + "&seedid=0";
		try {
			Element respXML = Network.getXMLResponse(url, KaiXinFarm.COOKIES).getRootElement();
			
			if ("succ".equals(respXML.getChildTextTrim("ret"))){
				if ("1".equals(respXML.getChildTextTrim("anti")))
					answerAntiQuestion();
				System.out.println("[" + Calendar.getInstance().getTime() + "]You have succeed to thieve " + respXML.getChildTextTrim("num") + " of " +
						farm.getOwner().getUserName() + "'s " + respXML.getChildTextTrim("seedname"));
				return true;
			} else {
				System.out.println("[" + Calendar.getInstance().getTime() + "]Failed to thieve " + farm.getOwner().getUserName() + "'s fruit! Farm num: " + farm.getFarmnum() + ", Reason: " + respXML.getChildTextTrim("reason"));
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	private void answerAntiQuestion(){
		
	}

	public long getDelay() {
		return delay;
	}

	public void setDelay(long delay) {
		this.delay = delay;
	}

	public Farm getFarm() {
		return farm;
	}

	public void setFarm(Farm farm) {
		this.farm = farm;
	}
}
